package com.today.cjl.sqlGen.utils

import java.io.PrintWriter

import scala.io.Source

/**
  * Created by cjl at 2018-09-03
  * Description: 
  * Changed: 
  */
object FileUtil extends CommonVar {

  /**
    * 读取行
    *
    * @param file 文件相对 resources/ 目录
    * @param trim 默认true 每行读取两头去空
    * @return
    */
  def readLine(file: String, trim: Boolean = true): List[String] = {
    val path: String = classPath(file)
    // 过滤掉空行和注释
    val filterMethod: String => Boolean = { str: String =>
      val trimStr: String = str.trim
      trimStr.nonEmpty && !trimStr.startsWith(IGNORE_LINE_SEP)
    }
    if (trim) Source.fromFile(path, "utf-8").getLines().filter(filterMethod).map(_.trim).toList
    else Source.fromFile(path, "utf-8").getLines().filter(filterMethod).toList
  }

  /**
    * 多行写入文件
    *
    * @param file
    * @param lines
    */
  def writeLine(file: String)(lines: List[String]): Unit = {
    val path: String = classPath(file)
    val writer: PrintWriter = new PrintWriter(path)
    try {
      lines.foreach(writer.println)
    } finally {
      writer.close()
    }
  }

  def classPath(absPath: String): String = {
    assert(absPath.isEmpty || !absPath.startsWith("/"))
    getClass.getResource("/").getPath + absPath
  }

}
